const app = getApp()
Page({
  data: {
    inputText: 'Kirby',
    inputText1:'576576576',
    receiveText: '',
    name: '',
    connectedDeviceId: '',
    services: {},
    characteristics: {},
    connected: true,
    type:'password',
    open: false,
    focus:false,
  },
  bindWifiId: function (e) {
    this.setData({
      inputText: e.detail.value
    })
    console.log(e.detail.value)
  },
  bindWifiPassword: function (e) {
    this.setData({
      inputText1: e.detail.value
    })
    console.log(e.detail.value)
  },
  
  Send: function () {
    var that = this
    if (that.data.connected) {//如果是在连接状态
      //wifi id
      var buffer = new ArrayBuffer(that.data.inputText.length)
      var dataView = new Uint8Array(buffer)
      for (var i = 0; i < that.data.inputText.length; i++) {
        dataView[i] = that.data.inputText.charCodeAt(i)
      }
      //wifi password
      var buffer1 = new ArrayBuffer(that.data.inputText1.length)
      var dataView1 = new Uint8Array(buffer1)
      for (var i = 0; i < that.data.inputText1.length; i++) {
        dataView1[i] = that.data.inputText1.charCodeAt(i)
      }
      //设置最大传输
      wx.setBLEMTU({
        deviceId: that.data.connectedDeviceId,
        mtu:512,
        success:(res)=>{
          console.log("setBLEMTU1 success>>", res)
        },
        fail:(res)=>{
          console.log("setBLEMTU1 fail>>", res)
        }
      })
      //写入特征值=发送
      wx.writeBLECharacteristicValue({
        deviceId: that.data.connectedDeviceId,
        serviceId: that.data.services[0].uuid,
        characteristicId: that.data.characteristics[0].uuid,
        writeType:'write',
        value: buffer,
        success: function (res) {
          console.log('发送wifi id成功')
          wx.showToast({
            title: 'wifi id 发送成功',
          })
          
          //监听特征值变化
          wx.notifyBLECharacteristicValueChange({
            state: true,
            deviceId: that.data.connectedDeviceId,
            serviceId: that.data.services[0].uuid,
            characteristicId: that.data.characteristics[0].uuid,
            type:'notification',
            success: function (res) {
              console.log('1启用notify成功')
              // wx.onBLECharacteristicValueChange(function (res) {
              //   console.log("1监听特征值变化>>",res);
              //   var receiveText = app.buf2string(res.value)
              //   console.log('第一次接收到数据：' + receiveText)
              //   that.setData({
              //     receiveText: receiveText
              //   })
              // })
            }
          })
        }
      })

     // 在发送成功后，延时2秒执行下一个写操作
    setTimeout(function () {
      wx.setBLEMTU({
        deviceId: that.data.connectedDeviceId,
        mtu:512,
        success:(res)=>{
          console.log("setBLEMTU2 success>>", res)
        },
        fail:(res)=>{
          console.log("setBLEMTU2 fail>>", res)
        }
      })
      wx.writeBLECharacteristicValue({
        deviceId: that.data.connectedDeviceId,
        serviceId: that.data.services[0].uuid,
        characteristicId: that.data.characteristics[0].uuid,
        value: buffer1,
        writeType:'write',
        success: function (res) {
          console.log("发送wifi password成功>>",res);
          wx.showToast({
            title: 'wifi密码发送成功',
          })
          setTimeout(function () {
              //监听特征值变化
            wx.notifyBLECharacteristicValueChange({
              state: true,
              deviceId: that.data.connectedDeviceId,
              serviceId: that.data.services[0].uuid,
              characteristicId: that.data.characteristics[0].uuid,
              type:'notification',
              success: function (res) {
                console.log('2启用notify成功')
                // wx.onBLECharacteristicValueChange(function (res) {
                //   console.log("2监听特征值变化>>",res);
                //   var receiveText = app.buf2string(res.value)
                //   console.log('第二次接收到数据：' + receiveText)
                //   that.setData({
                //     receiveText: receiveText
                //   })
                // })
              }
            })
          }, 1000); // 1秒延时
        },
        fail: function (res) {
          console.error('第二次发送失败', res);
        }
      });
    }, 500); // 1秒延时
      
    }
    else {
      wx.showModal({
        title: '提示',
        content: '蓝牙已断开',
        showCancel: false,
        success: function (res) {
          that.setData({
            searching: false
          })
        }
      })
    }
  },
  onLoad: function (options) {
    var that = this
    console.log(options)
    that.setData({
      name: options.name,
      connectedDeviceId: options.connectedDeviceId
    })
    wx.getBLEDeviceServices({
      deviceId: that.data.connectedDeviceId,
      success: function (res) {
        console.log(res.services)
        that.setData({
          services: res.services
        })
        wx.getBLEDeviceCharacteristics({

          deviceId: options.connectedDeviceId,
          serviceId: res.services[0].uuid,
          success: function (res) {
            console.log(res)
            console.log(res.characteristics)
            that.setData({
              characteristics: res.characteristics
            })
            wx.setBLEMTU({
              deviceId: that.data.connectedDeviceId,
              mtu:512,
              success:(res)=>{
                console.log("setBLEMTU2 success>>", res)
              },
              fail:(res)=>{
                console.log("setBLEMTU2 fail>>", res)
              }
            })
            wx.notifyBLECharacteristicValueChange({
              state: true,
              deviceId: options.connectedDeviceId,
              serviceId: that.data.services[0].uuid,
              characteristicId: that.data.characteristics[0].uuid,
              success: function (res) {
                console.log('启用全局notify成功')
              }
            })
          }
        })
      }
    })
    //监听全局变化
    wx.onBLEConnectionStateChange(function (res) {
      console.log(res.connected)
      that.setData({
        connected: res.connected
      })
    })
    wx.onBLECharacteristicValueChange(function (res) {
      var receiveText = app.buf2string(res.value)
      console.log('接收到全局数据：' + receiveText)
      that.setData({
        receiveText: receiveText
      })
      const regex = /^[0-9A-F]{12}$/;
      if (regex.test(receiveText)) {
        wx.request({
          url: 'http://114.132.70.44:2000/add_device',
          method:'POST',
          data:{'id':receiveText}
        });
        wx.navigateBack({
          delta: 3, 
        });
      }
    })
  },
  onReady: function () {

  },
  onShow: function () {

  },
  onHide: function () {

  },
  switch() {
    this.setData({
      open: !this.data.open
    })
  },
  focus(){
    this.setData({
      focus:true
    })
  },
  blur(){
    this.setData({
      focus:false
    })
  },
})